package com.noteit.login;  
  
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import org.apache.struts2.ServletActionContext;  
import org.springframework.beans.factory.annotation.Autowired;
  
import com.noteit.bean.Account;
import com.noteit.dao.LoginDAO;
import com.opensymphony.xwork2.ActionSupport;
  
public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = 3797931674267685888L;
	private String userName;  
	private String password;
	private int loginTimes;
	private String birthday;
	private String telephone;
	private String telephone2;
	private String address;
	private String address2;
	private String deleteflag;
	private Date createdate;
	private Date lastlogindate;
	private String gmailAccountValidate = "";
	private Account acnt;
	@Autowired
	private LoginDAO loginDAO;
	public static String serviceType="cl"; //ServiceType see more in http://code.google.com/intl/zh-TW/apis/gdata/faq.html#clientlogin
	URL url;

	//all struts logic here
	public String execute() {
		 ServletActionContext.getRequest().getSession().setAttribute("loggedInUser", userName);  
		 
		 try {
			 gmailAccountValidate = googleLoginVerify(userName,password);
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
		
		 if(gmailAccountValidate.equalsIgnoreCase("validateOK")){
			 try {
				saveUserData(userName,password);
				return "login-success";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "input";
			}
		      
		 }else{
			 return "input";
		 }

	}
	
	//saveOrUpdate user to account db
	public String saveUserData(String gmailAccount, String passwd){
		Account acnt = new Account();
		
		//check this account exist or not.
		String isExistRAW = null;
		try {
			isExistRAW = loginDAO.checkAccountExist(gmailAccount);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(isExistRAW.equalsIgnoreCase("[0]")){
			//isNew Account, Insert into db.
			acnt.setUserName(gmailAccount);
			acnt.setPassword(passwd);
			acnt.setDeleteflag("N");
			acnt.setCreatedate(new Date());
			
		}else{
			//already exist Account, update things.
			System.out.println("account exist");
			acnt.setUserName(gmailAccount);
			acnt.setPassword(passwd);
			acnt.setBirthday(birthday);
			acnt.setTelephone(telephone);
			acnt.setTelephone2(telephone2);
			acnt.setAddress(address);
			acnt.setAddress2(address2);
			acnt.setDeleteflag("N");
			acnt.setCreatedate(createdate);
			acnt.setLastlogindate(new Date());
		}
		
		try {
			loginDAO.saveAccountInfo(acnt);
			return "success";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "input";
		}
		
		
	}
	
	public String googleLoginVerify(String gmail, String passwd) throws IOException{
		
		System.out.println("gamil="+gmail+", passwd="+passwd);
		if((gmail.length()>0 && !gmail.isEmpty()) && (passwd.length()>0 && !passwd.isEmpty())){
			String data = "accountType=HOSTED_OR_GOOGLE"+
			"&Email="+gmail+
			"&Passwd="+passwd+
			"&service="+serviceType+
			"&source=Gulp-CalGulp-1.05"; 

			try {
			url = new URL("https://www.google.com/accounts/ClientLogin");
			
			/// Open Connect
			URLConnection conn = url.openConnection(); 
			
			/// setDoOutput=true than can write message to sent request
			conn.setDoOutput(true); 
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
			BufferedReader rd = null;
				try {
					/// Get the response
					rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
					String line;
					
					while ((line = rd.readLine()) != null) {
						// Process line...
						System.out.println(line);
					}
					wr.close();
					rd.close();
				} catch (Exception e) {
					System.out.println("err1:"+e.getMessage());
					//e.printStackTrace();
					return "input";
				} finally{
					wr.close();
					//rd.close();
				}
						
			}catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				System.out.println("err2:"+e.getMessage());
				//e.printStackTrace();
				return "input";
			}
			
			return "validateOK";
		}else{
			return "validateFail";
		}
	}
	  
	 // simple validation  
	public void validate() {
		 if(userName.trim().equalsIgnoreCase("") || password.trim().equalsIgnoreCase("")) {
			 addActionError("Username and Password cann't be blanked");  
		 }  
		 else {
			 addActionMessage("You are valid user!");  
		 }
	}
	
	public Account getAcnt() {
		return acnt;
	}
	public void setAcnt(Account acnt) {
		this.acnt = acnt;
	}
	public String getUserName() {
	 return userName;  
	}  
	public void setUserName(String userName) {  
	 this.userName = userName;  
	}  
	public String getPassword() {  
	 return password;  
	}  
	public void setPassword(String password) {  
	 this.password = password;  
	}
	
	public int getLoginTimes() {
		return loginTimes;
	}

	public void setLoginTimes(int loginTimes) {
		this.loginTimes = loginTimes;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getTelephone2() {
		return telephone2;
	}

	public void setTelephone2(String telephone2) {
		this.telephone2 = telephone2;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getAddress2() {
		return address2;
	}

	public void setAddress2(String address2) {
		this.address2 = address2;
	}

	public String getDeleteflag() {
		return deleteflag;
	}

	public void setDeleteflag(String deleteflag) {
		this.deleteflag = deleteflag;
	}

	public Date getCreatedate() {
		return createdate;
	}

	public void setCreatedate(Date createdate) {
		this.createdate = createdate;
	}

	public Date getLastlogindate() {
		return lastlogindate;
	}

	public void setLastlogindate(Date lastlogindate) {
		this.lastlogindate = lastlogindate;
	}

	public String getGmailAccountValidate() {
		return gmailAccountValidate;
	}
	public void setGmailAccountValidate(String gmailAccountValidate) {
		this.gmailAccountValidate = gmailAccountValidate;
	}
} 